

<!DOCTYPE html>
<html lang="zh-CN" data-default-color-scheme=auto>



<head>
  <meta charset="UTF-8">
  <link rel="apple-touch-icon" sizes="76x76" href="/img/fluid.png">
  <link rel="icon" href="/img/fluid.png">
  <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=5.0, shrink-to-fit=no">
  <meta http-equiv="x-ua-compatible" content="ie=edge">
  
  <meta name="theme-color" content="#2f4154">
  <meta name="author" content="叶飞">
  <meta name="keywords" content="">
  
    <meta name="description" content="1 regexp struct 1234567891011121314151617181920212223242526&#x2F;&#x2F; Regexp is the representation of a compiled regular expression.&#x2F;&#x2F; A Regexp is safe for concurrent use by multiple goroutines,&#x2F;&#x2F; except for">
<meta property="og:type" content="article">
<meta property="og:title" content="Golang-Regexp">
<meta property="og:url" content="http://example.com/2022/05/29/20220529-Golang-Regexp/index.html">
<meta property="og:site_name" content="博客">
<meta property="og:description" content="1 regexp struct 1234567891011121314151617181920212223242526&#x2F;&#x2F; Regexp is the representation of a compiled regular expression.&#x2F;&#x2F; A Regexp is safe for concurrent use by multiple goroutines,&#x2F;&#x2F; except for">
<meta property="og:locale" content="zh_CN">
<meta property="article:published_time" content="2022-05-29T02:03:14.000Z">
<meta property="article:modified_time" content="2022-05-29T02:41:34.659Z">
<meta property="article:author" content="叶飞">
<meta property="article:tag" content="regexp">
<meta name="twitter:card" content="summary_large_image">
  
  
  
  <title>Golang-Regexp - 博客</title>

  <link  rel="stylesheet" href="https://lib.baomitu.com/twitter-bootstrap/4.6.1/css/bootstrap.min.css" />



  <link  rel="stylesheet" href="https://lib.baomitu.com/github-markdown-css/4.0.0/github-markdown.min.css" />

  <link  rel="stylesheet" href="https://lib.baomitu.com/hint.css/2.7.0/hint.min.css" />

  <link  rel="stylesheet" href="https://lib.baomitu.com/fancybox/3.5.7/jquery.fancybox.min.css" />



<!-- 主题依赖的图标库，不要自行修改 -->
<!-- Do not modify the link that theme dependent icons -->

<link rel="stylesheet" href="//at.alicdn.com/t/font_1749284_hj8rtnfg7um.css">



<link rel="stylesheet" href="//at.alicdn.com/t/font_1736178_lbnruvf0jn.css">


<link  rel="stylesheet" href="/css/main.css" />


  <link id="highlight-css" rel="stylesheet" href="/css/highlight.css" />
  
    <link id="highlight-css-dark" rel="stylesheet" href="/css/highlight-dark.css" />
  




  <script id="fluid-configs">
    var Fluid = window.Fluid || {};
    Fluid.ctx = Object.assign({}, Fluid.ctx)
    var CONFIG = {"hostname":"example.com","root":"/","version":"1.9.2","typing":{"enable":true,"typeSpeed":70,"cursorChar":"_","loop":false,"scope":[]},"anchorjs":{"enable":true,"element":"h1,h2,h3,h4,h5,h6","placement":"left","visible":"hover","icon":""},"progressbar":{"enable":true,"height_px":3,"color":"#29d","options":{"showSpinner":false,"trickleSpeed":100}},"code_language":{"enable":true,"default":"TEXT"},"copy_btn":true,"image_caption":{"enable":true},"image_zoom":{"enable":true,"img_url_replace":["",""]},"toc":{"enable":true,"placement":"right","headingSelector":"h1,h2,h3,h4,h5,h6","collapseDepth":0},"lazyload":{"enable":true,"loading_img":"/img/loading.gif","onlypost":false,"offset_factor":2},"web_analytics":{"enable":false,"follow_dnt":true,"baidu":null,"google":null,"gtag":null,"tencent":{"sid":null,"cid":null},"woyaola":null,"cnzz":null,"leancloud":{"app_id":null,"app_key":null,"server_url":null,"path":"window.location.pathname","ignore_local":false}},"search_path":"/local-search.xml"};

    if (CONFIG.web_analytics.follow_dnt) {
      var dntVal = navigator.doNotTrack || window.doNotTrack || navigator.msDoNotTrack;
      Fluid.ctx.dnt = dntVal && (dntVal.startsWith('1') || dntVal.startsWith('yes') || dntVal.startsWith('on'));
    }
  </script>
  <script  src="/js/utils.js" ></script>
  <script  src="/js/color-schema.js" ></script>
  


  
<meta name="generator" content="Hexo 6.2.0"></head>


<body>
  

  <header>
    

<div class="header-inner" style="height: 70vh;">
  <nav id="navbar" class="navbar fixed-top  navbar-expand-lg navbar-dark scrolling-navbar">
  <div class="container">
    <a class="navbar-brand" href="/">
      <strong>No Tomorrow</strong>
    </a>

    <button id="navbar-toggler-btn" class="navbar-toggler" type="button" data-toggle="collapse"
            data-target="#navbarSupportedContent"
            aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
      <div class="animated-icon"><span></span><span></span><span></span></div>
    </button>

    <!-- Collapsible content -->
    <div class="collapse navbar-collapse" id="navbarSupportedContent">
      <ul class="navbar-nav ml-auto text-center">
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/">
                <i class="iconfont icon-home-fill"></i>
                首页
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/archives/">
                <i class="iconfont icon-archive-fill"></i>
                归档
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/categories/">
                <i class="iconfont icon-category-fill"></i>
                分类
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/tags/">
                <i class="iconfont icon-tags-fill"></i>
                标签
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/about/">
                <i class="iconfont icon-user-fill"></i>
                关于
              </a>
            </li>
          
        
        
          <li class="nav-item" id="search-btn">
            <a class="nav-link" target="_self" href="javascript:;" data-toggle="modal" data-target="#modalSearch" aria-label="Search">
              &nbsp;<i class="iconfont icon-search"></i>&nbsp;
            </a>
          </li>
          
        
        
          <li class="nav-item" id="color-toggle-btn">
            <a class="nav-link" target="_self" href="javascript:;" aria-label="Color Toggle">&nbsp;<i
                class="iconfont icon-dark" id="color-toggle-icon"></i>&nbsp;</a>
          </li>
        
      </ul>
    </div>
  </div>
</nav>

  

<div id="banner" class="banner" parallax=true
     style="background: url('/img/default.png') no-repeat center center; background-size: cover;">
  <div class="full-bg-img">
    <div class="mask flex-center" style="background-color: rgba(0, 0, 0, 0.3)">
      <div class="banner-text text-center fade-in-up">
        <div class="h2">
          
            <span id="subtitle" data-typed-text="Golang-Regexp"></span>
          
        </div>

        
          
  <div class="mt-3">
    
      <span class="post-meta mr-2">
        <i class="iconfont icon-author" aria-hidden="true"></i>
        叶飞
      </span>
    
    
      <span class="post-meta">
        <i class="iconfont icon-date-fill" aria-hidden="true"></i>
        <time datetime="2022-05-29 10:03" pubdate>
          星期日, 五月 29日 2022, 10:03 上午
        </time>
      </span>
    
  </div>

  <div class="mt-1">
    
      <span class="post-meta mr-2">
        <i class="iconfont icon-chart"></i>
        
          <!-- compatible with older versions-->
          8.8k 字
        
      </span>
    

    
      <span class="post-meta mr-2">
        <i class="iconfont icon-clock-fill"></i>
        
        
        
          <!-- compatible with older versions-->
          74 分钟
        
      </span>
    

    
    
      
        <span id="leancloud-page-views-container" class="post-meta" style="display: none">
          <i class="iconfont icon-eye" aria-hidden="true"></i>
          <span id="leancloud-page-views"></span> 次
        </span>
        
      
    
  </div>


        
      </div>

      
    </div>
  </div>
</div>

</div>

  </header>

  <main>
    
      

<div class="container-fluid nopadding-x">
  <div class="row nomargin-x">
    <div class="side-col d-none d-lg-block col-lg-2">
      

    </div>

    <div class="col-lg-8 nopadding-x-md">
      <div class="container nopadding-x-md" id="board-ctn">
        <div id="board">
          <article class="post-content mx-auto">
            <!-- SEO header -->
            <h1 style="display: none">Golang-Regexp</h1>
            
            
              <div class="markdown-body">
                
                <h2 id="1-regexp-struct"><a class="markdownIt-Anchor" href="#1-regexp-struct"></a> 1 regexp struct</h2>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br></pre></td><td class="code"><pre><code class="hljs go"><span class="hljs-comment">// Regexp is the representation of a compiled regular expression.</span><br><span class="hljs-comment">// A Regexp is safe for concurrent use by multiple goroutines,</span><br><span class="hljs-comment">// except for configuration methods, such as Longest.</span><br><span class="hljs-comment">// Regexp是编译后的正则表达式   Re2语法</span><br><span class="hljs-comment">// 正则对象是并发安全的</span><br><span class="hljs-keyword">type</span> Regexp <span class="hljs-keyword">struct</span> &#123;<br>	expr           <span class="hljs-type">string</span>       <span class="hljs-comment">// 正则表达式</span><br>	prog           *syntax.Prog <span class="hljs-comment">// compiled program</span><br>	onepass        *onePassProg <span class="hljs-comment">// onepass program or nil</span><br>	numSubexp      <span class="hljs-type">int</span><br>	maxBitStateLen <span class="hljs-type">int</span><br>	subexpNames    []<span class="hljs-type">string</span><br>	prefix         <span class="hljs-type">string</span>         <span class="hljs-comment">// required prefix in unanchored matches</span><br>	prefixBytes    []<span class="hljs-type">byte</span>         <span class="hljs-comment">// prefix, as a []byte</span><br>	prefixRune     <span class="hljs-type">rune</span>           <span class="hljs-comment">// first rune in prefix</span><br>	prefixEnd      <span class="hljs-type">uint32</span>         <span class="hljs-comment">// pc for last rune in prefix</span><br>	mpool          <span class="hljs-type">int</span>            <span class="hljs-comment">// pool for machines</span><br>	matchcap       <span class="hljs-type">int</span>            <span class="hljs-comment">// size of recorded match lengths</span><br>	prefixComplete <span class="hljs-type">bool</span>           <span class="hljs-comment">// prefix is the entire regexp</span><br>	cond           syntax.EmptyOp <span class="hljs-comment">// empty-width conditions required at start of match</span><br>	minInputLen    <span class="hljs-type">int</span>            <span class="hljs-comment">// minimum length of the input in bytes</span><br><br>	<span class="hljs-comment">// This field can be modified by the Longest method,</span><br>	<span class="hljs-comment">// but it is otherwise read-only.</span><br>	longest <span class="hljs-type">bool</span> <span class="hljs-comment">// whether regexp prefers leftmost-longest match</span><br>&#125;<br></code></pre></td></tr></table></figure>
<h2 id="2-签名"><a class="markdownIt-Anchor" href="#2-签名"></a> 2 签名</h2>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br></pre></td><td class="code"><pre><code class="hljs go"><span class="hljs-comment">// 返回正则对象的源文本</span><br><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-params">(re *Regexp)</span></span> String() <span class="hljs-type">string</span><br><br><span class="hljs-comment">// 返回一个re的副本  已经不推荐使用，早期使用是为了避免协程之前竞争</span><br><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-params">(re *Regexp)</span></span> Copy() *Regexp<br><br><span class="hljs-comment">// Compile 解析expr这个正则表达式，并返回结果</span><br><span class="hljs-comment">// 作用：将表达式编译成【正则对象】 默认longest=false</span><br><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">Compile</span><span class="hljs-params">(expr <span class="hljs-type">string</span>)</span></span> (*Regexp, <span class="hljs-type">error</span>)&#123;<br>    <span class="hljs-keyword">return</span> compile(expr, syntax.Perl, <span class="hljs-literal">false</span>)<br>&#125;<br><br><span class="hljs-comment">// 将正则表达式编译成一个正则对象（正则语法限制在 POSIX ERE 范围内）。</span><br><span class="hljs-comment">// 该正则对象会采用“leftmost-longest”模式。选择最长的匹配结果。</span><br><span class="hljs-comment">// POSIX 语法不支持 Perl 的语法格式：\d、\D、\s、\S、\w、\W</span><br><span class="hljs-comment">// 如果正则表达式语法错误，则返回错误信息。</span><br><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">CompilePOSIX</span><span class="hljs-params">(expr <span class="hljs-type">string</span>)</span></span> (*Regexp, <span class="hljs-type">error</span>)<br><br><span class="hljs-comment">// 功能同上，但会在解析失败时 panic</span><br><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">MustCompile</span><span class="hljs-params">(str <span class="hljs-type">string</span>)</span></span> *Regexp<br><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">MustCompilePOSIX</span><span class="hljs-params">(str <span class="hljs-type">string</span>)</span></span> *Regexp<br><br><span class="hljs-comment">// 让正则表达式在之后的搜索中都采用“leftmost-longest”模式。</span><br><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-params">(re *Regexp)</span></span> Longest()<br><br><span class="hljs-comment">// 返回编译时使用的正则表达式字符串</span><br><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-params">(re *Regexp)</span></span> String() <span class="hljs-type">string</span><br><br><span class="hljs-comment">// 返回正则表达式中分组的数量</span><br><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-params">(re *Regexp)</span></span> NumSubexp() <span class="hljs-type">int</span><br><br><span class="hljs-comment">// 返回正则表达式中分组的名字</span><br><span class="hljs-comment">// 第 0 个元素表示整个正则表达式的名字，永远是空字符串。</span><br><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-params">(re *Regexp)</span></span> SubexpNames() []<span class="hljs-type">string</span><br><br><span class="hljs-comment">// 返回正则表达式必须匹配到的字面前缀（不包含可变部分）。</span><br><span class="hljs-comment">// 如果整个正则表达式都是字面值，则 complete 返回 true。</span><br><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-params">(re *Regexp)</span></span> LiteralPrefix() (prefix <span class="hljs-type">string</span>, complete <span class="hljs-type">bool</span>)<br><br><span class="hljs-comment">// 判断</span><br><br><span class="hljs-comment">// 判断在 b（s、r）中能否找到匹配的字符串</span><br><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-params">(re *Regexp)</span></span> Match(b []<span class="hljs-type">byte</span>) <span class="hljs-type">bool</span><br><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-params">(re *Regexp)</span></span> MatchString(s <span class="hljs-type">string</span>) <span class="hljs-type">bool</span><br><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-params">(re *Regexp)</span></span> MatchReader(r io.RuneReader) <span class="hljs-type">bool</span><br><br><span class="hljs-comment">// 查找</span><br><br><span class="hljs-comment">// 返回第一个匹配到的结果（结果以 b 的切片形式返回）。</span><br><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-params">(re *Regexp)</span></span> Find(b []<span class="hljs-type">byte</span>) []<span class="hljs-type">byte</span><br><br><span class="hljs-comment">// 返回第一个匹配到的结果及其分组内容（结果以 b 的切片形式返回）。</span><br><span class="hljs-comment">// 返回值中的第 0 个元素是整个正则表达式的匹配结果，后续元素是各个分组的</span><br><span class="hljs-comment">// 匹配内容，分组顺序按照“(”的出现次序而定。</span><br><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-params">(re *Regexp)</span></span> FindSubmatch(b []<span class="hljs-type">byte</span>) [][]<span class="hljs-type">byte</span><br><br><span class="hljs-comment">// 功能同 Find，只不过返回的是匹配结果的首尾下标，通过这些下标可以生成切片。</span><br><span class="hljs-comment">// loc[0] 是结果切片的起始下标，loc[1] 是结果切片的结束下标。</span><br><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-params">(re *Regexp)</span></span> FindIndex(b []<span class="hljs-type">byte</span>) (loc []<span class="hljs-type">int</span>)<br><br><span class="hljs-comment">// 功能同 FindSubmatch，只不过返回的是匹配结果的首尾下标，通过这些下标可以生成切片。</span><br><span class="hljs-comment">// loc[0] 是结果切片的起始下标，loc[1] 是结果切片的结束下标。</span><br><span class="hljs-comment">// loc[2] 是分组1切片的起始下标，loc[3] 是分组1切片的结束下标。</span><br><span class="hljs-comment">// loc[4] 是分组2切片的起始下标，loc[5] 是分组2切片的结束下标。</span><br><span class="hljs-comment">// 以此类推</span><br><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-params">(re *Regexp)</span></span> FindSubmatchIndex(b []<span class="hljs-type">byte</span>) (loc []<span class="hljs-type">int</span>)<br></code></pre></td></tr></table></figure>
<h2 id="3-examples"><a class="markdownIt-Anchor" href="#3-examples"></a> 3 Examples</h2>
<h3 id="1-第一匹配和最长匹配"><a class="markdownIt-Anchor" href="#1-第一匹配和最长匹配"></a> 1. 第一匹配和最长匹配</h3>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><code class="hljs go"><span class="hljs-comment">// 示例：第一匹配和最长匹配</span><br><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">main</span><span class="hljs-params">()</span></span> &#123;<br>	b := []<span class="hljs-type">byte</span>(<span class="hljs-string">&quot;abc1def1&quot;</span>)<br>	pat := <span class="hljs-string">`abc1|abc1def1`</span><br>	reg1 := regexp.MustCompile(pat)      <span class="hljs-comment">// 第一匹配</span><br>	reg2 := regexp.MustCompilePOSIX(pat) <span class="hljs-comment">// 最长匹配</span><br>	fmt.Printf(<span class="hljs-string">&quot;%s\n&quot;</span>, reg1.Find(b))     <span class="hljs-comment">// abc1</span><br>	fmt.Printf(<span class="hljs-string">&quot;%s\n&quot;</span>, reg2.Find(b))     <span class="hljs-comment">// abc1def1</span><br><br>	b = []<span class="hljs-type">byte</span>(<span class="hljs-string">&quot;abc1def1&quot;</span>)<br>	pat = <span class="hljs-string">`(abc|abc1def)*1`</span><br>	reg1 = regexp.MustCompile(pat)      <span class="hljs-comment">// 第一匹配</span><br>	reg2 = regexp.MustCompilePOSIX(pat) <span class="hljs-comment">// 最长匹配</span><br>	fmt.Printf(<span class="hljs-string">&quot;%s\n&quot;</span>, reg1.Find(b))    <span class="hljs-comment">// abc1</span><br>	fmt.Printf(<span class="hljs-string">&quot;%s\n&quot;</span>, reg2.Find(b))    <span class="hljs-comment">// abc1def1</span><br>&#125;<br><br></code></pre></td></tr></table></figure>
<h3 id="2-正则信息"><a class="markdownIt-Anchor" href="#2-正则信息"></a> 2. 正则信息</h3>
<hr>
<p>// 示例：正则信息<br>
func main() {<br>
pat := <code>(abc)(def)(ghi)</code><br>
reg := regexp.MustCompile(pat)</p>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br></pre></td><td class="code"><pre><code class="hljs go"><span class="hljs-comment">// 获取正则表达式字符串</span><br>fmt.Println(reg.String())    <span class="hljs-comment">// (abc)(def)(ghi)</span><br><br><span class="hljs-comment">// 获取分组数量</span><br>fmt.Println(reg.NumSubexp()) <span class="hljs-comment">// 3</span><br><br>fmt.Println()<br><br><span class="hljs-comment">// 获取分组名称</span><br>pat = <span class="hljs-string">`(?P&lt;Name1&gt;abc)(def)(?P&lt;Name3&gt;ghi)`</span><br>reg = regexp.MustCompile(pat)<br><br><span class="hljs-keyword">for</span> i := <span class="hljs-number">0</span>; i &lt;= reg.NumSubexp(); i++ &#123;<br>	fmt.Printf(<span class="hljs-string">&quot;%d: %q\n&quot;</span>, i, reg.SubexpNames()[i])<br>&#125;<br><span class="hljs-comment">// 0: &quot;&quot;</span><br><span class="hljs-comment">// 1: &quot;Name1&quot;</span><br><span class="hljs-comment">// 2: &quot;&quot;</span><br><span class="hljs-comment">// 3: &quot;Name3&quot;</span><br><br>fmt.Println()<br><br><span class="hljs-comment">// 获取字面前缀</span><br>pat = <span class="hljs-string">`(abc1)(abc2)(abc3)`</span><br>reg = regexp.MustCompile(pat)<br>fmt.Println(reg.LiteralPrefix()) <span class="hljs-comment">// abc1abc2abc3 true</span><br><br>pat = <span class="hljs-string">`(abc1)|(abc2)|(abc3)`</span><br>reg = regexp.MustCompile(pat)<br>fmt.Println(reg.LiteralPrefix()) <span class="hljs-comment">//  false</span><br><br>pat = <span class="hljs-string">`abc1|abc2|abc3`</span><br>reg = regexp.MustCompile(pat)<br>fmt.Println(reg.LiteralPrefix()) <span class="hljs-comment">// abc false</span><br></code></pre></td></tr></table></figure>
<p>}</p>
<hr>
<h3 id="3-查找-匹配"><a class="markdownIt-Anchor" href="#3-查找-匹配"></a> 3. 查找-匹配</h3>
<hr>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><code class="hljs go"><span class="hljs-comment">// 查找</span><br><br><span class="hljs-comment">// 返回第一个匹配到的结果（结果以 b 的切片形式返回）。</span><br><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-params">(re *Regexp)</span></span> Find(b []<span class="hljs-type">byte</span>) []<span class="hljs-type">byte</span><br><br><span class="hljs-comment">// 返回第一个匹配到的结果及其分组内容（结果以 b 的切片形式返回）。</span><br><span class="hljs-comment">// 返回值中的第 0 个元素是整个正则表达式的匹配结果，后续元素是各个分组的</span><br><span class="hljs-comment">// 匹配内容，分组顺序按照“(”的出现次序而定。</span><br><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-params">(re *Regexp)</span></span> FindSubmatch(b []<span class="hljs-type">byte</span>) [][]<span class="hljs-type">byte</span><br><br><span class="hljs-comment">// 功能同 Find，只不过返回的是匹配结果的首尾下标，通过这些下标可以生成切片。</span><br><span class="hljs-comment">// loc[0] 是结果切片的起始下标，loc[1] 是结果切片的结束下标。</span><br><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-params">(re *Regexp)</span></span> FindIndex(b []<span class="hljs-type">byte</span>) (loc []<span class="hljs-type">int</span>)<br><br><span class="hljs-comment">// 功能同 FindSubmatch，只不过返回的是匹配结果的首尾下标，通过这些下标可以生成切片。</span><br><span class="hljs-comment">// loc[0] 是结果切片的起始下标，loc[1] 是结果切片的结束下标。</span><br><span class="hljs-comment">// loc[2] 是分组1切片的起始下标，loc[3] 是分组1切片的结束下标。</span><br><span class="hljs-comment">// loc[4] 是分组2切片的起始下标，loc[5] 是分组2切片的结束下标。</span><br><span class="hljs-comment">// 以此类推</span><br><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-params">(re *Regexp)</span></span> FindSubmatchIndex(b []<span class="hljs-type">byte</span>) (loc []<span class="hljs-type">int</span>)<br></code></pre></td></tr></table></figure>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><code class="hljs go"><span class="hljs-comment">// 示例：Find、FindSubmatch</span><br><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">main</span><span class="hljs-params">()</span></span> &#123;<br>	pat := <span class="hljs-string">`(((abc.)def.)ghi)`</span><br>	reg := regexp.MustCompile(pat)<br><br>	src := []<span class="hljs-type">byte</span>(<span class="hljs-string">`abc-def-ghi abc+def+ghi`</span>)<br>	<br>	<span class="hljs-comment">// 查找第一个匹配结果</span><br>	fmt.Printf(<span class="hljs-string">&quot;%s\n&quot;</span>, reg.Find(src)) <span class="hljs-comment">// abc-def-ghi</span><br>	<br>	fmt.Println()<br>	<br>	<span class="hljs-comment">// 查找第一个匹配结果及其分组字符串</span><br>	first := reg.FindSubmatch(src)<br>	<span class="hljs-keyword">for</span> i := <span class="hljs-number">0</span>; i &lt; <span class="hljs-built_in">len</span>(first); i++ &#123;<br>		fmt.Printf(<span class="hljs-string">&quot;%d: %s\n&quot;</span>, i, first[i])<br>	&#125;<br>	<span class="hljs-comment">// 0: abc-def-ghi</span><br>	<span class="hljs-comment">// 1: abc-def-ghi</span><br>	<span class="hljs-comment">// 2: abc-def-</span><br>	<span class="hljs-comment">// 3: abc-</span><br><br>&#125;<br></code></pre></td></tr></table></figure>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br></pre></td><td class="code"><pre><code class="hljs go"><span class="hljs-comment">// 示例：FindIndex、FindSubmatchIndex</span><br><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">main</span><span class="hljs-params">()</span></span> &#123;<br>	pat := <span class="hljs-string">`(((abc.)def.)ghi)`</span><br>	reg := regexp.MustCompile(pat)<br><br>	src := []<span class="hljs-type">byte</span>(<span class="hljs-string">`abc-def-ghi abc+def+ghi`</span>)<br>	<br>	<span class="hljs-comment">// 查找第一个匹配结果</span><br>	matched := reg.FindIndex(src)<br>	fmt.Printf(<span class="hljs-string">&quot;%v\n&quot;</span>, matched) <span class="hljs-comment">// [0 11]</span><br>	m := matched[<span class="hljs-number">0</span>]<br>	n := matched[<span class="hljs-number">1</span>]<br>	fmt.Printf(<span class="hljs-string">&quot;%s\n\n&quot;</span>, src[m:n]) <span class="hljs-comment">// abc-def-ghi</span><br>	<br>	<span class="hljs-comment">// 查找第一个匹配结果及其分组字符串</span><br>	matched = reg.FindSubmatchIndex(src)<br>	fmt.Printf(<span class="hljs-string">&quot;%v\n&quot;</span>, matched) <span class="hljs-comment">// [0 11 0 11 0 8 0 4]</span><br>	<span class="hljs-keyword">for</span> i := <span class="hljs-number">0</span>; i &lt; <span class="hljs-built_in">len</span>(matched)/<span class="hljs-number">2</span>; i++ &#123;<br>		m := matched[i*<span class="hljs-number">2</span>]<br>		n := matched[i*<span class="hljs-number">2</span>+<span class="hljs-number">1</span>]<br>		fmt.Printf(<span class="hljs-string">&quot;%s\n&quot;</span>, src[m:n])<br>	&#125;<br>	<span class="hljs-comment">// abc-def-ghi</span><br>	<span class="hljs-comment">// abc-def-ghi</span><br>	<span class="hljs-comment">// abc-def-</span><br>	<span class="hljs-comment">// abc-</span><br><br>&#125;<br></code></pre></td></tr></table></figure>
<h3 id="4-查找匹配"><a class="markdownIt-Anchor" href="#4-查找匹配"></a> 4. 查找匹配</h3>
<hr>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><code class="hljs go"><span class="hljs-comment">// 功能同上，只不过返回多个匹配的结果，而不只是第一个。</span><br><span class="hljs-comment">// n 是查找次数，负数表示不限次数。</span><br><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-params">(re *Regexp)</span></span> FindAll(b []<span class="hljs-type">byte</span>, n <span class="hljs-type">int</span>) [][]<span class="hljs-type">byte</span><br><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-params">(re *Regexp)</span></span> FindAllSubmatch(b []<span class="hljs-type">byte</span>, n <span class="hljs-type">int</span>) [][][]<span class="hljs-type">byte</span><br><br><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-params">(re *Regexp)</span></span> FindAllIndex(b []<span class="hljs-type">byte</span>, n <span class="hljs-type">int</span>) [][]<span class="hljs-type">int</span><br><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-params">(re *Regexp)</span></span> FindAllSubmatchIndex(b []<span class="hljs-type">byte</span>, n <span class="hljs-type">int</span>) [][]<span class="hljs-type">int</span><br></code></pre></td></tr></table></figure>
<hr>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br></pre></td><td class="code"><pre><code class="hljs go"><br><br><span class="hljs-comment">// 示例：FindAll、FindAllSubmatch</span><br><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">main</span><span class="hljs-params">()</span></span> &#123;<br>	pat := <span class="hljs-string">`(((abc.)def.)ghi)`</span><br>	reg := regexp.MustCompile(pat)<br><br>	s := []<span class="hljs-type">byte</span>(<span class="hljs-string">`abc-def-ghi abc+def+ghi`</span>)<br>	<br>	<span class="hljs-comment">// 查找所有匹配结果</span><br>	<span class="hljs-keyword">for</span> _, one := <span class="hljs-keyword">range</span> reg.FindAll(s, <span class="hljs-number">-1</span>) &#123;<br>		fmt.Printf(<span class="hljs-string">&quot;%s\n&quot;</span>, one)<br>	&#125;<br>	<span class="hljs-comment">// abc-def-ghi</span><br>	<span class="hljs-comment">// abc+def+ghi</span><br>	<br>	<span class="hljs-comment">// 查找所有匹配结果及其分组字符串</span><br>	all := reg.FindAllSubmatch(s, <span class="hljs-number">-1</span>)<br>	<span class="hljs-keyword">for</span> i := <span class="hljs-number">0</span>; i &lt; <span class="hljs-built_in">len</span>(all); i++ &#123;<br>		fmt.Println()<br>		one := all[i]<br>		<span class="hljs-keyword">for</span> i := <span class="hljs-number">0</span>; i &lt; <span class="hljs-built_in">len</span>(one); i++ &#123;<br>			fmt.Printf(<span class="hljs-string">&quot;%d: %s\n&quot;</span>, i, one[i])<br>		&#125;<br>	&#125;<br>	<span class="hljs-comment">// 0: abc-def-ghi</span><br>	<span class="hljs-comment">// 1: abc-def-ghi</span><br>	<span class="hljs-comment">// 2: abc-def-</span><br>	<span class="hljs-comment">// 3: abc-</span><br>	<br>	<span class="hljs-comment">// 0: abc+def+ghi</span><br>	<span class="hljs-comment">// 1: abc+def+ghi</span><br>	<span class="hljs-comment">// 2: abc+def+</span><br>	<span class="hljs-comment">// 3: abc+</span><br><br>&#125;<br></code></pre></td></tr></table></figure>
<hr>
<h3 id="5-字符串查找匹配"><a class="markdownIt-Anchor" href="#5-字符串查找匹配"></a> 5. 字符串查找匹配</h3>
<hr>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><code class="hljs go"><br><br><span class="hljs-comment">// 功能同上，只不过在字符串中查找</span><br><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-params">(re *Regexp)</span></span> FindString(s <span class="hljs-type">string</span>) <span class="hljs-type">string</span><br><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-params">(re *Regexp)</span></span> FindStringSubmatch(s <span class="hljs-type">string</span>) []<span class="hljs-type">string</span><br><br><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-params">(re *Regexp)</span></span> FindStringIndex(s <span class="hljs-type">string</span>) (loc []<span class="hljs-type">int</span>)<br><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-params">(re *Regexp)</span></span> FindStringSubmatchIndex(s <span class="hljs-type">string</span>) []<span class="hljs-type">int</span><br><br><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-params">(re *Regexp)</span></span> FindAllString(s <span class="hljs-type">string</span>, n <span class="hljs-type">int</span>) []<span class="hljs-type">string</span><br><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-params">(re *Regexp)</span></span> FindAllStringSubmatch(s <span class="hljs-type">string</span>, n <span class="hljs-type">int</span>) [][]<span class="hljs-type">string</span><br><br><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-params">(re *Regexp)</span></span> FindAllStringIndex(s <span class="hljs-type">string</span>, n <span class="hljs-type">int</span>) [][]<span class="hljs-type">int</span><br><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-params">(re *Regexp)</span></span> FindAllStringSubmatchIndex(s <span class="hljs-type">string</span>, n <span class="hljs-type">int</span>) [][]<span class="hljs-type">int</span><br><br><span class="hljs-comment">// 功能同上，只不过在 io.RuneReader 中查找。</span><br><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-params">(re *Regexp)</span></span> FindReaderIndex(r io.RuneReader) (loc []<span class="hljs-type">int</span>)<br><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-params">(re *Regexp)</span></span> FindReaderSubmatchIndex(r io.RuneReader) []<span class="hljs-type">int</span><br></code></pre></td></tr></table></figure>
<hr>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br></pre></td><td class="code"><pre><code class="hljs go"><br><br><span class="hljs-comment">// 替换（不会修改参数，结果是参数的副本）</span><br><br><span class="hljs-comment">// 将 src 中匹配的内容替换为 repl（repl 中可以使用 $1 $name 等分组引用符）。</span><br><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-params">(re *Regexp)</span></span> ReplaceAll(src, repl []<span class="hljs-type">byte</span>) []<span class="hljs-type">byte</span><br><br><span class="hljs-comment">// 将 src 中匹配的内容经过 repl 函数处理后替换回去。</span><br><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-params">(re *Regexp)</span></span> ReplaceAllFunc(src []<span class="hljs-type">byte</span>, repl <span class="hljs-function"><span class="hljs-keyword">func</span><span class="hljs-params">([]<span class="hljs-type">byte</span>)</span></span> []<span class="hljs-type">byte</span>) []<span class="hljs-type">byte</span><br><br><span class="hljs-comment">// 将 src 中匹配的内容替换为 repl（repl 为字面值，不解析其中的 $1 $name 等）。</span><br><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-params">(re *Regexp)</span></span> ReplaceAllLiteral(src, repl []<span class="hljs-type">byte</span>) []<span class="hljs-type">byte</span><br><br><span class="hljs-comment">// 功能同上，只不过在字符串中查找。</span><br><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-params">(re *Regexp)</span></span> ReplaceAllString(src, repl <span class="hljs-type">string</span>) <span class="hljs-type">string</span><br><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-params">(re *Regexp)</span></span> ReplaceAllStringFunc(src <span class="hljs-type">string</span>, repl <span class="hljs-function"><span class="hljs-keyword">func</span><span class="hljs-params">(<span class="hljs-type">string</span>)</span></span> <span class="hljs-type">string</span>) <span class="hljs-type">string</span><br><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-params">(re *Regexp)</span></span> ReplaceAllLiteralString(src, repl <span class="hljs-type">string</span>) <span class="hljs-type">string</span><br><br><span class="hljs-comment">// Expand 要配合 FindSubmatchIndex 一起使用。FindSubmatchIndex 在 src 中进行</span><br><span class="hljs-comment">// 查找，将结果存入 match 中。这样就可以通过 src 和 match 得到匹配的字符串。</span><br><span class="hljs-comment">// template 是替换内容，可以使用分组引用符 $1、$2、$name 等。Expane 将其中的分</span><br><span class="hljs-comment">// 组引用符替换为前面匹配到的字符串。然后追加到 dst 的尾部（dst 可以为空）。</span><br><span class="hljs-comment">// 说白了 Expand 就是一次替换过程，只不过需要 FindSubmatchIndex 的配合。</span><br><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-params">(re *Regexp)</span></span> Expand(dst []<span class="hljs-type">byte</span>, template []<span class="hljs-type">byte</span>, src []<span class="hljs-type">byte</span>, match []<span class="hljs-type">int</span>) []<span class="hljs-type">byte</span><br><br><span class="hljs-comment">// 功能同上，参数为字符串。</span><br><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-params">(re *Regexp)</span></span> ExpandString(dst []<span class="hljs-type">byte</span>, template <span class="hljs-type">string</span>, src <span class="hljs-type">string</span>, match []<span class="hljs-type">int</span>) []<span class="hljs-type">byte</span><br></code></pre></td></tr></table></figure>
<hr>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br></pre></td><td class="code"><pre><code class="hljs go"><br><br><span class="hljs-comment">// 示例：Expand</span><br><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">main</span><span class="hljs-params">()</span></span> &#123;<br>	pat := <span class="hljs-string">`(((abc.)def.)ghi)`</span><br>	reg := regexp.MustCompile(pat)<br><br>	src := []<span class="hljs-type">byte</span>(<span class="hljs-string">`abc-def-ghi abc+def+ghi`</span>)<br>	template := []<span class="hljs-type">byte</span>(<span class="hljs-string">`$0   $1   $2   $3`</span>)<br>	<br>	<span class="hljs-comment">// 替换第一次匹配结果</span><br>	match := reg.FindSubmatchIndex(src)<br>	fmt.Printf(<span class="hljs-string">&quot;%v\n&quot;</span>, match) <span class="hljs-comment">// [0 11 0 11 0 8 0 4]</span><br>	dst := reg.Expand(<span class="hljs-literal">nil</span>, template, src, match)<br>	fmt.Printf(<span class="hljs-string">&quot;%s\n\n&quot;</span>, dst)<br>	<span class="hljs-comment">// abc-def-ghi   abc-def-ghi   abc-def-   abc-</span><br>	<br>	<span class="hljs-comment">// 替换所有匹配结果</span><br>	<span class="hljs-keyword">for</span> _, match := <span class="hljs-keyword">range</span> reg.FindAllSubmatchIndex(src, <span class="hljs-number">-1</span>) &#123;<br>		fmt.Printf(<span class="hljs-string">&quot;%v\n&quot;</span>, match)<br>		dst := reg.Expand(<span class="hljs-literal">nil</span>, template, src, match)<br>		fmt.Printf(<span class="hljs-string">&quot;%s\n&quot;</span>, dst)<br>	&#125;<br>	<span class="hljs-comment">// [0 11 0 11 0 8 0 4]</span><br>	<span class="hljs-comment">// abc-def-ghi   abc-def-ghi   abc-def-   abc-</span><br>	<span class="hljs-comment">// [12 23 12 23 12 20 12 16]</span><br>	<span class="hljs-comment">// abc+def+ghi   abc+def+ghi   abc+def+   abc+</span><br><br>&#125;<br></code></pre></td></tr></table></figure>
<hr>
<p>// 其它</p>
<p>// 以 s 中的匹配结果作为分割符将 s 分割成字符串列表。<br>
// n 是分割次数，负数表示不限次数。<br>
func (re *Regexp) Split(s string, n int) []string</p>
<p>// 将当前正则对象复制一份。在多例程中使用同一正则对象时，给每个例程分配一个<br>
// 正则对象的副本，可以避免多例程对单个正则对象的争夺锁定。<br>
func (re *Regexp) Copy() *Regexp</p>
<hr>

                
              </div>
            
            <hr/>
            <div>
              <div class="post-metas my-3">
  
    <div class="post-meta mr-3 d-flex align-items-center">
      <i class="iconfont icon-category"></i>
      

<span class="category-chains">
  
  
    
      <span class="category-chain">
        
  <a href="/categories/Golang/" class="category-chain-item">Golang</a>
  
  
    <span>></span>
    
  <a href="/categories/Golang/%E5%B8%B8%E7%94%A8%E5%8C%85/" class="category-chain-item">常用包</a>
  
  

  

      </span>
    
  
</span>

    </div>
  
  
    <div class="post-meta">
      <i class="iconfont icon-tags"></i>
      
        <a href="/tags/regexp/">#regexp</a>
      
    </div>
  
</div>


              
  

  <div class="license-box my-3">
    <div class="license-title">
      <div>Golang-Regexp</div>
      <div>http://example.com/2022/05/29/20220529-Golang-Regexp/</div>
    </div>
    <div class="license-meta">
      
        <div class="license-meta-item">
          <div>作者</div>
          <div>叶飞</div>
        </div>
      
      
        <div class="license-meta-item license-meta-date">
          <div>发布于</div>
          <div>2022年5月29日</div>
        </div>
      
      
      <div class="license-meta-item">
        <div>许可协议</div>
        <div>
          
            
            
              <a target="_blank" href="https://creativecommons.org/licenses/by/4.0/">
              <span class="hint--top hint--rounded" aria-label="BY - 署名">
                <i class="iconfont icon-by"></i>
              </span>
              </a>
            
          
        </div>
      </div>
    </div>
    <div class="license-icon iconfont"></div>
  </div>



              
                <div class="post-prevnext my-3">
                  <article class="post-prev col-6">
                    
                    
                      <a href="/2022/06/29/20220629-gopacket/" title="gopacket基本使用">
                        <i class="iconfont icon-arrowleft"></i>
                        <span class="hidden-mobile">gopacket基本使用</span>
                        <span class="visible-mobile">上一篇</span>
                      </a>
                    
                  </article>
                  <article class="post-next col-6">
                    
                    
                      <a href="/2022/05/19/20220519-%E6%9C%8D%E5%8A%A1%E5%99%A8%E8%BF%90%E8%A1%8Celasticsearch%E7%88%86%E5%86%85%E5%AD%98/" title="服务器运行elasticsearch爆内存">
                        <span class="hidden-mobile">服务器运行elasticsearch爆内存</span>
                        <span class="visible-mobile">下一篇</span>
                        <i class="iconfont icon-arrowright"></i>
                      </a>
                    
                  </article>
                </div>
              
            </div>

            
          </article>
        </div>
      </div>
    </div>

    <div class="side-col d-none d-lg-block col-lg-2">
      
  <aside class="sidebar" style="margin-left: -1rem">
    <div id="toc">
  <p class="toc-header"><i class="iconfont icon-list"></i>&nbsp;目录</p>
  <div class="toc-body" id="toc-body"></div>
</div>



  </aside>


    </div>
  </div>
</div>





  



  



  



  



  


  
  









    

    
      <a id="scroll-top-button" aria-label="TOP" href="#" role="button">
        <i class="iconfont icon-arrowup" aria-hidden="true"></i>
      </a>
    

    
      <div class="modal fade" id="modalSearch" tabindex="-1" role="dialog" aria-labelledby="ModalLabel"
     aria-hidden="true">
  <div class="modal-dialog modal-dialog-scrollable modal-lg" role="document">
    <div class="modal-content">
      <div class="modal-header text-center">
        <h4 class="modal-title w-100 font-weight-bold">搜索</h4>
        <button type="button" id="local-search-close" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body mx-3">
        <div class="md-form mb-5">
          <input type="text" id="local-search-input" class="form-control validate">
          <label data-error="x" data-success="v" for="local-search-input">关键词</label>
        </div>
        <div class="list-group" id="local-search-result"></div>
      </div>
    </div>
  </div>
</div>

    

    
  </main>

  <footer>
    <div class="footer-inner">
  
    <div class="footer-content">
       <a href="https://hexo.io" target="_blank" rel="nofollow noopener"><span>Hexo</span></a> <i class="iconfont icon-love"></i> <a href="https://github.com/fluid-dev/hexo-theme-fluid" target="_blank" rel="nofollow noopener"><span>Fluid</span></a> 
    </div>
  
  
  
  
</div>

  </footer>

  <!-- Scripts -->
  
  <script  src="https://lib.baomitu.com/nprogress/0.2.0/nprogress.min.js" ></script>
  <link  rel="stylesheet" href="https://lib.baomitu.com/nprogress/0.2.0/nprogress.min.css" />

  <script>
    NProgress.configure({"showSpinner":false,"trickleSpeed":100})
    NProgress.start()
    window.addEventListener('load', function() {
      NProgress.done();
    })
  </script>


<script  src="https://lib.baomitu.com/jquery/3.6.0/jquery.min.js" ></script>
<script  src="https://lib.baomitu.com/twitter-bootstrap/4.6.1/js/bootstrap.min.js" ></script>
<script  src="/js/events.js" ></script>
<script  src="/js/plugins.js" ></script>


  <script  src="https://lib.baomitu.com/typed.js/2.0.12/typed.min.js" ></script>
  <script>
    (function (window, document) {
      var typing = Fluid.plugins.typing;
      var subtitle = document.getElementById('subtitle');
      if (!subtitle || !typing) {
        return;
      }
      var text = subtitle.getAttribute('data-typed-text');
      
        typing(text);
      
    })(window, document);
  </script>




  
    <script  src="/js/img-lazyload.js" ></script>
  




  
<script>
  Fluid.utils.createScript('https://lib.baomitu.com/tocbot/4.18.2/tocbot.min.js', function() {
    var toc = jQuery('#toc');
    if (toc.length === 0 || !window.tocbot) { return; }
    var boardCtn = jQuery('#board-ctn');
    var boardTop = boardCtn.offset().top;

    window.tocbot.init({
      tocSelector     : '#toc-body',
      contentSelector : '.markdown-body',
      headingSelector : CONFIG.toc.headingSelector || 'h1,h2,h3,h4,h5,h6',
      linkClass       : 'tocbot-link',
      activeLinkClass : 'tocbot-active-link',
      listClass       : 'tocbot-list',
      isCollapsedClass: 'tocbot-is-collapsed',
      collapsibleClass: 'tocbot-is-collapsible',
      collapseDepth   : CONFIG.toc.collapseDepth || 0,
      scrollSmooth    : true,
      headingsOffset  : -boardTop
    });
    if (toc.find('.toc-list-item').length > 0) {
      toc.css('visibility', 'visible');
    }
  });
</script>


  <script src=https://lib.baomitu.com/clipboard.js/2.0.10/clipboard.min.js></script>

  <script>Fluid.plugins.codeWidget();</script>


  
<script>
  Fluid.utils.createScript('https://lib.baomitu.com/anchor-js/4.3.1/anchor.min.js', function() {
    window.anchors.options = {
      placement: CONFIG.anchorjs.placement,
      visible  : CONFIG.anchorjs.visible
    };
    if (CONFIG.anchorjs.icon) {
      window.anchors.options.icon = CONFIG.anchorjs.icon;
    }
    var el = (CONFIG.anchorjs.element || 'h1,h2,h3,h4,h5,h6').split(',');
    var res = [];
    for (var item of el) {
      res.push('.markdown-body > ' + item.trim());
    }
    if (CONFIG.anchorjs.placement === 'left') {
      window.anchors.options.class = 'anchorjs-link-left';
    }
    window.anchors.add(res.join(', '));
  });
</script>


  
<script>
  Fluid.utils.createScript('https://lib.baomitu.com/fancybox/3.5.7/jquery.fancybox.min.js', function() {
    Fluid.plugins.fancyBox();
  });
</script>


  <script>Fluid.plugins.imageCaption();</script>

  
      <script>
        if (!window.MathJax) {
          window.MathJax = {
            tex    : {
              inlineMath: { '[+]': [['$', '$']] }
            },
            loader : {
              load: ['ui/lazy']
            },
            options: {
              renderActions: {
                insertedScript: [200, () => {
                  document.querySelectorAll('mjx-container').forEach(node => {
                    let target = node.parentNode;
                    if (target.nodeName.toLowerCase() === 'li') {
                      target.parentNode.classList.add('has-jax');
                    }
                  });
                }, '', false]
              }
            }
          };
        } else {
          MathJax.startup.document.state(0);
          MathJax.texReset();
          MathJax.typeset();
          MathJax.typesetPromise();
        }
      </script>
    

  <script  src="https://lib.baomitu.com/mathjax/3.2.1/es5/tex-mml-chtml.js" ></script>

  <script  src="/js/local-search.js" ></script>

  <script defer src="/js/leancloud.js" ></script>





<!-- 主题的启动项，将它保持在最底部 -->
<!-- the boot of the theme, keep it at the bottom -->
<script  src="/js/boot.js" ></script>


  

  <noscript>
    <div class="noscript-warning">博客在允许 JavaScript 运行的环境下浏览效果更佳</div>
  </noscript>
<script src="/live2dw/lib/L2Dwidget.min.js?094cbace49a39548bed64abff5988b05"></script><script>L2Dwidget.init({"log":false,"pluginJsPath":"lib/","pluginModelPath":"assets/","pluginRootPath":"live2dw/","tagMode":false});</script></body>
</html>
